<?php

namespace App\Admin\Controllers;

use App\Broker;
use App\BrokerLevel;
use App\Http\Controllers\Controller;
use App\model\BrokerMobile;
use App\Service\TeleService;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\MessageBag;

class BrokerController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('经纪人列表')
            ->description('')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('Detail')
            ->description('description')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('经纪人编辑')
            ->description('')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('创建经纪人')
            ->description('')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Broker);

        $grid->id('Id');
        $grid->name('名称');
        $grid->atvar('头像')->display(function($value){
             $url= Storage::url($value);
            return "<img src='{$url}' width='100px' height='100px'>";
        });
        $grid->true_mobile('真实号码');
        $grid->bind_mobile('绑定号码');
        $grid->wechat('微信号');

        $grid->level_id('等级名称')->display(function($value){
            return BrokerLevel::find($value)->level_name ?? '无';
        });
        $grid->created_at('申请时间');

        $grid->filter(function (Grid\Filter $filter) {
            $filter->disableIdFilter();
            $filter->like('name', '用户名称');
            $filter->like('true_mobile', '手机号');

        });
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Broker::findOrFail($id));

        $show->id('Id');
        $show->name('Name');
        $show->atvar('Atvar');
        $show->true_mobile('True mobile');
        $show->bind_mobile('Bind mobile');
        $show->wechat('Wechat');
        $show->created_at('Created at');
        $show->level_id('Level id');
        $show->updated_at('Updated at');
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Broker);

        $form->text('name', '经纪人名称')->rules('required',[
            'required'=>'请填写经纪人名称'
        ]);
        $form->image('atvar', '头像');
        $form->mobile('true_mobile', '真实手机号')->rules('mobile',[
            'mobile'=>'请输入真实手机号'
        ]);
        //$form->select('broker_mobile_id','绑定手机号')->options(BrokerMobile::getSelectOptions());
        $form->hidden('seqId')->default($this->createdSeqId());
        $form->text('wechat', '微信号');
        $form->select('level_id', '等级')->options(BrokerLevel::getSelectOptions());
        /*$form->saving(function (Form $form){
          if ($form->broker_mobile_id) {
          $tele= new TeleService();
           $brokerMobile= BrokerMobile::find($form->broker_mobile_id);
          $broker= Broker::where('bind_mobile',$brokerMobile->mobile)->first();
          if($broker&&$broker->true_mobile!=$form->true_mobile){
              $error = new MessageBag([
                  'title'   => '该商务号已经绑定别的手机',
                  'message' => '',
              ]);
              return back()->with(compact('error'))->withInput();
          }
           try {
               $tele->setSpInfo();
               //先解除绑定
               if($broker&&$broker->true_mobile==$form->true_mobile){
                   $tele->unbindMobile($form->true_mobile, $brokerMobile->mobile);
               }
               //绑定
               try{
                  $value= $tele->searchBindMobile($brokerMobile->mobile);
                  $tele->unbindMobile($value['value'], $brokerMobile->mobile);
                   $brokerMobile->is_bind=0;
                   $brokerMobile->save();
               }catch (\Exception $e){

               }
               $result=$tele->bindMobile($form->seqId, $form->true_mobile,$brokerMobile->mobile);
               $brokerMobile->is_bind=1;
               $brokerMobile->save();
           }catch (\Exception $e){
               $error = new MessageBag([
                   'title'   => $e->getMessage(),
                   'message' => $e->getMessage(),
               ]);

               return back()->with(compact('error'));
           }
          }
        });
        $form->saved(function(Form $form){
            if($form->broker_mobile_id) {
                $brokerMobile = BrokerMobile::find($form->broker_mobile_id);
                $broker = Broker::find($form->model()->id);
                $broker->bind_mobile = $brokerMobile->mobile;
                $broker->save();
            }
        });*/
        return $form;
    }
    public function destroy($id)
    {

        $tele= new TeleService();
        $broker=Broker::find($id);
        if($broker->bind_mobile){
        try {
            $tele->unbindMobile($broker->true_mobile, $broker->bind_mobile);
            $brokerMobile=BrokerMobile::find($broker->broker_mobile_id);
            $brokerMobile->is_bind=0;
            $brokerMobile->save();
        }catch (\Exception $e){
            $data = [
                'status'  => false,
                'message' => $e->getMessage(),
            ];
        }
        }
        if ($this->form()->destroy($id)) {
            $data = [
                'status'  => true,
                'message' => trans('admin.delete_succeeded'),
            ];
        } else {
            $data = [
                'status'  => false,
                'message' => trans('admin.delete_failed'),
            ];
        }

        return response()->json($data);
    }
    protected function createdSeqId(){
        return uniqid();
    }
}
